import _ from 'lodash'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { compose } from 'common/util'
import { Form } from 'antd'

const noop = () => ({})

export const formcontainer = (formOpt, props, mapDispatchToProps = noop) => target => {
    const chain = [withRouter]

    if (formOpt !== false) {
        chain.push(Form.create(typeof formOpt === 'object' ? formOpt : {}))
    }

    const { propSelectors, defaultProps } = target
    const mapStateToProps = state => {
        const rs = _.chain(propSelectors)
            .toPairs()
            .map(([alias, key]) => {
                let v = _.get(state, key, defaultProps[alias])
                if (_.isObject(v)) {
                    v = {
                        ...defaultProps[alias],
                        ...v,
                    }
                }
                return [alias, v]
            })
            .fromPairs()
            .value()
        return rs
    }

    chain.push(connect(mapStateToProps))


    return compose(...chain)(target)
}

export default (...args) => formcontainer(false, ...args)

